import { loginApi, refreshTokenApi } from '@/api/login'
import { LoginParams, Token } from '@/types/http'
import { getToken, removeToken, setToken } from '@/utils/token'
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// state
const initialState: Token = getToken()

// reducers
const reducers = {

}

const loginSlice = createSlice({
  name: 'login',
  initialState,
  reducers,
  extraReducers: (builder) => {
    builder.addCase(loginAsync.fulfilled, (state, action) => {
      // 存储到本地
      setToken(action.payload)
      // 存储到redux
      return action.payload
    })

    builder.addCase(removeTokenAsync.fulfilled, (state, action) => {
      return action.payload
    })

    builder.addCase(refreshTokenAsync.fulfilled, (state, action) => {
      state.token = action.payload
    })
  }
})

// 登录action
export const loginAsync = createAsyncThunk(
  'login/login',
  async (data: LoginParams, { rejectWithValue }) => {
    try {
      const { data: {
        data: token
      } } = await loginApi(data)
      return token
    } catch (e) {
      return rejectWithValue(e)
    }
  }
)

// 删除redux和本地 token
export const removeTokenAsync = createAsyncThunk(
  'login/removeTokenAsync',
  () => {
    removeToken()
    return {
      token: '',
      refresh_token: ''
    }
  }
)

// 异步刷新token
export const refreshTokenAsync = createAsyncThunk(
  'login/refreshTokenAsync',
  async (refresh_token: string) => {
    // 请求新token
    const { data: {
      data: {
        token
      }
    } } = await refreshTokenApi(refresh_token)

    const newToken: Token = {
      token,
      refresh_token
    }
    // 新token同步到本地
    setToken(newToken)

    // 返回值同步到redux
    return token
  }
)

export default loginSlice.reducer